package com.yaozheng.vocationaltraining.view;

import java.util.Calendar;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.BaseActivity;
import com.yaozheng.vocationaltraining.dialog.interfaces.BaseDialogEventProcess;
import com.yaozheng.vocationaltraining.iview.IHomeSignTaskView;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 主页签到view
 *
 * @author Administrator
 */
@EViewGroup(R.layout.view_dialog_home_sign_task)
public class HomeSignTaskView extends LinearLayout implements View.OnClickListener {
    BaseDialogEventProcess baseDialog;

    /**
     * 签到一项
     */
    SignItemMonthView[] signItemMonthViews;
    @ViewById
    View signItemMonthFrame6;

    JSONObject dataJsonObject;

    IHomeSignTaskView iHomeSignTaskView;
    @ViewById
    TextView headTitleText, headRightText;
    @ViewById
    TextView homeSignTaskCloseButton;


    int firstDayOfWeek;
    int lastDay;
    int currDay;
    int month;
    int selectIndex;

    private BaseActivity baseActivity;

    SignItemMonthView lastSignItemMonthView;

    SignItemMonthView retroactivMonthView;
    public final static String[] MONTHS = new String
            []
            {
                    "Jan", "Feb", "Mar",
                    "April", "May", "Jun", "Jul",
                    "Aug", "Sep", "Oct", "Nov", "Dec",
            };

    public BaseDialogEventProcess getBaseDialog() {
        return baseDialog;
    }

    public void setBaseDialog(BaseDialogEventProcess baseDialog) {
        this.baseDialog = baseDialog;
    }

    public IHomeSignTaskView getiHomeSignTaskView() {
        return iHomeSignTaskView;
    }

    public void setiHomeSignTaskView(IHomeSignTaskView iHomeSignTaskView) {
        this.iHomeSignTaskView = iHomeSignTaskView;
    }


    public HomeSignTaskView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.baseActivity = (BaseActivity) context;
    }

    public HomeSignTaskView(Context context) {
        super(context);
        this.baseActivity = (BaseActivity) context;
    }

    public void initHead(Calendar currCalendar) {
        headTitleText.setText("签到");
        month = currCalendar.get(Calendar.MONTH);
        try {
            headRightText.setText(MONTHS[month] + " " + currCalendar.get(Calendar.YEAR));
            headRightText.setVisibility(View.VISIBLE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @AfterViews
    public void initView() {
        selectIndex = -1;
        signItemMonthViews = new SignItemMonthView[42];
        Calendar lastCalendar = Calendar.getInstance();
        initHead(lastCalendar);
        currDay = lastCalendar.get(Calendar.DATE);
        lastCalendar.set(Calendar.DATE, 1);// 设为当前月的1号
        firstDayOfWeek = lastCalendar.get(Calendar.DAY_OF_WEEK) - 1;//得到星期
//        firstDayOfWeek = firstDayOfWeek == 0 ? 7 : firstDayOfWeek;
//        firstDayOfWeek=1;
        lastCalendar.add(Calendar.MONTH, 1);// 加一个月，变为下月的1号
        lastCalendar.add(Calendar.DATE, -1);// 减去一天，变为当月最后一天
        lastDay = lastCalendar.get(Calendar.DATE);

        if (firstDayOfWeek == 6 || firstDayOfWeek == 7) {
            //星期五 星期六 把最后一行显示
            signItemMonthFrame6.setVisibility(View.VISIBLE);
        } else {
            signItemMonthFrame6.setVisibility(View.GONE);
        }
        for (int i = 1; i <= signItemMonthViews.length; i++) {

            SignItemMonthView signItemMonthView = (SignItemMonthView) findViewById(getResources()
                    .getIdentifier("signItemMonthView" + i, "id",
                            "com.yaozheng.vocationaltraining"));
            signItemMonthView.setTag(R.id.tag_index, i - 1);
            signItemMonthView.setOnClickListener(this);
            signItemMonthViews[i - 1] = signItemMonthView;
            int value = i - firstDayOfWeek;
            signItemMonthView.setValue(String.valueOf(value));

            if (value >= 1 && value <= lastDay) {
                signItemMonthView.setVisibility(View.VISIBLE);
            } else {
                signItemMonthView.setVisibility(View.INVISIBLE);
            }
        }


    }

    public void loadData(JSONObject dataJsonObject) {
        // {"error_code":0,"data":{"box_positions":["20160307","20160313","20160325"],"signed_days":[["20160316","0"]]}}
        JSONArray box_positionsJsonArray = TypeUtils.getJsonArray(
                dataJsonObject, "box_positions");
        JSONArray signed_daysJsonArray = TypeUtils.getJsonArray(dataJsonObject,
                "signed_days");
        Calendar date = Calendar.getInstance();
        int currDay = date.get(Calendar.DAY_OF_MONTH);
        int year = date.get(Calendar.YEAR);
        int month = date.get(Calendar.MONTH) + 1;
        String dataStr = year + "" + (month < 10 ? "0" + month : month);
        if (box_positionsJsonArray != null) {
            for (int i = firstDayOfWeek; i < lastDay; i++) {
                SignItemMonthView signItemMonthView = signItemMonthViews[i];
                int day = i - firstDayOfWeek + 1;
                signItemMonthView.setCurrDay(day);
                String dayStr = dataStr + (day < 10 ? "0" + day : day);
                signItemMonthView.setSignDate(dayStr);
                boolean hideDatabase = true;
                for (int j = 0; j < TypeUtils
                        .getJsonArraySize(box_positionsJsonArray); j++) {

                    String positionStr = TypeUtils.getJsonString(
                            box_positionsJsonArray, j);
                    if (dayStr.equals(positionStr)) {
                        signItemMonthView.showDatabase();
                        hideDatabase = false;
                        break;
                    }
                }
                if (hideDatabase) {
                    signItemMonthView.hideDatabase();
                }
                for (int j = 0; j < TypeUtils
                        .getJsonArraySize(signed_daysJsonArray); j++) {
                    JSONArray itemJsonArray = TypeUtils.getJsonArray(
                            signed_daysJsonArray, j);
                    if (dayStr
                            .equals(TypeUtils.getJsonString(itemJsonArray, 0))) {
                        signItemMonthView.signIn();
                        break;
                    }
                }

                signItemMonthView.loadData(currDay == (i - firstDayOfWeek + 1));
            }
        }
        SignItemMonthView signItemMonthView = signItemMonthViews[currDay + firstDayOfWeek - 1];
        if (signItemMonthView.isSign()) {
            homeSignTaskCloseButton.setBackgroundResource(R.drawable.icon_close_bg);
        } else {
            homeSignTaskCloseButton.setBackgroundResource(R.drawable.icon_sign_image1);
        }
    }

    @Click({R.id.homeSignTaskCloseButton})
    public void closeButton() {

        Calendar date = Calendar.getInstance();
        int year = date.get(Calendar.YEAR);
        int month = date.get(Calendar.MONTH) + 1;
        int day = date.get(Calendar.DAY_OF_MONTH);
        LogUtils.println("day=" + day + ";firstDayOfWeek=" + firstDayOfWeek);
        SignItemMonthView signItemMonthView = signItemMonthViews[day + firstDayOfWeek - 1];
        if (signItemMonthView.isSign()) {
            baseDialog.runMethod("cancelDialog");
        } else {
            String dateStr = year + "" + (month < 10 ? "0" + month : month)
                    + "" + (day < 10 ? "0" + day : day);
            iHomeSignTaskView.executeSign(dateStr);
        }

    }


    @Override
    public void onClick(View v) {
        selectIndex = (Integer) v.getTag(R.id.tag_index);
        SignItemMonthView currSignItemMonthView = signItemMonthViews[selectIndex];
        if (lastSignItemMonthView != null) {
            lastSignItemMonthView.unRetroactive();
            if (currSignItemMonthView == lastSignItemMonthView) {
                lastSignItemMonthView = null;
                return;
            }
        }
        lastSignItemMonthView = currSignItemMonthView;
        lastSignItemMonthView.retroactive();
        LogUtils.println("selectIndex=" + selectIndex);
    }


    /**
     * 补签
     */
    @Click(R.id.homeRetroactiveTextView)
    public void retroactiveClick() {
        if (selectIndex == -1) {
            baseActivity.alertMessage("请选择补签日期");
        } else {
            retroactivMonthView = signItemMonthViews[selectIndex];
            if (!retroactivMonthView.isSign()) {
                Calendar date = Calendar.getInstance();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) + 1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                int retroactiveDay = retroactivMonthView.getCurrDay();
                if (day <= retroactiveDay) {
                    baseActivity.showCancelAskDialog("不能对未来日期进行签到", "抱歉", null);
                } else {
                    baseActivity.showConfirmCancelAskDialog("补签需要消耗积分", "retroactiveOperating");
                }
            } else {
                baseActivity.alertMessage("已经签到");
            }
        }
    }

    /**
     * 补签操作
     */
    public void retroactiveOperating() {
        if (retroactivMonthView != null) {
            SignItemMonthView signItemMonthView = this.signItemMonthViews[selectIndex];
            if (!signItemMonthView.isSign()) {
                Calendar date = Calendar.getInstance();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) + 1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                int retroactiveDay = signItemMonthView.getCurrDay();
                if (day <= retroactiveDay) {
                    baseActivity.showCancelAskDialog("不能对未来日期进行签到", "抱歉", null);
                } else {

                    String dateStr = year + "" + (month < 10 ? "0" + month : month)
                            + "" + (retroactiveDay < 10 ? "0" + retroactiveDay : retroactiveDay);
                    iHomeSignTaskView.executeSign(dateStr);

                }
            } else {
                baseActivity.alertMessage("已经签到");
            }


        }
    }

}
